#!/usr/bin/python
# -*- coding: UTF-8 -*-
"""
@author:durant.zeng
@file:redisUtils.py
@time:2020/09/27
"""
import redis
import sys
import os
from common.read_data import data
from common.logger import logger

BASE_PATH = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
sys.path.append(BASE_PATH)

data_file_path = os.path.join(BASE_PATH, "config", "setting.ini")
data = data.load_ini(data_file_path)["redis"]

DB_CONF = {
    "host": data["REDIS_HOST"],
    "port": int(data["REDIS_PORT"]),
    "password": data["REDIS_PASSWD"],
}



class RedisDb:

    def __init__(self,host,port,password):
        '''
        初始化
        :param host:
        :param port:
        :param password:
        '''
        try:
            self.r = redis.StrictRedis(host=host,port=port,password=password,decode_responses=True)
            logger.info("redis连接成功")
        except Exception as e:
            logger.error("redis连接失败,错误信息为%s" %e)


    # def __init__(self,db_conf=DB_CONF):
    #     '''
    #     初始化
    #     :param host:
    #     :param port:
    #     :param password:
    #     '''
    #     try:
    #         self.r = redis.StrictRedis(**db_conf,decode_responses=True)
    #     except Exception as e:
    #         logger.info("redis连接失败,错误信息为%s" %e)


    def get_value(self,key):
        '''
        获取key的值
        :param key:
        :return:
        '''
        res = self.r.get(key)
        return res

    def get_ttl(self,key):
        '''
        获取key的过期时间
        :param key:
        :return:
        '''
        return self.r.ttl(key)


    def set_key_value(self,key,value):
        '''
        往redis中设值
        :param key:
        :param value:
        :return:
        '''
        self.r.set(key,value)


# db = RedisDb(DB_CONF)
# session_id = "1647508676940"
# key = "VERIFY:{0}".format(session_id)
# res = db.get_value(key)
# print(res)

if __name__ == '__main__':
    REDIS_HOST = "192.168.1.5"
    REDIS_PORT = 6379
    REDIS_PASSWD ="b@30QpqPkh"
    db = RedisDb(REDIS_HOST,REDIS_PORT,REDIS_PASSWD)
    print(db)
    session_id = "1647508676940"
    key = "VERIFY_PIC:{0}".format(session_id)
    res = db.get_value(key)
    print(res)
